﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using CbtcVirtualNet;
using System.Threading;

namespace ZCConsole
{
    public class ZCSocket
    {
        Dictionary<int, UdpClient> clientMap = new Dictionary<int, UdpClient>();

        /// <summary>
        /// ZC 把发送给联锁的逻辑区段占用信息转发出去
        /// </summary>
        private UdpClient logicSectionClient = new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6003));

        internal HandleData VOBCorCI;
        private ZC zc;

        internal ZCSocket(ZC zc)
        {
            this.zc = zc;
            VOBCorCI = new HandleData(zc);
            IPConfigure iPConfigure = new IPConfigure();  //将ZC与其他设备端口进行connect
            foreach (var item in iPConfigure.IPList)
            {
                UdpClient client = new UdpClient(new IPEndPoint(item.LocalIp, item.LocalPort));
                client.Connect(item.IP, item.Port);
                clientMap[item.DeviceID] = client;
            }

            logicSectionClient.Connect("127.0.0.1", 6030);
        }

        /// <summary>
        /// 开始抓包并进行数据处理
        /// </summary>
        public void Start()
        {
            IPEndPoint sender = null;

            foreach (var client in clientMap.Values)
            {
                Thread thread = new Thread(() =>
                {
                    while (true)
                    {
                        try
                        {
                            byte[] buf = client.Receive(ref sender);
                            SaveData(buf);
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(e.Message);
                        }
                    }
                })
                { IsBackground = true };
                thread.Start();
            }
        }

        /// <summary>
        /// 处理数据
        /// </summary>
        /// <param name="receiveDataArray"></param>
        private void SaveData(byte[] receiveDataArray)
        {
            if (receiveDataArray != null)
            {
                VOBCorCI.Handle(receiveDataArray, zc, this);
            }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="buf"></param>
        /// <param name="len"></param>
        /// <param name="deviceId"></param>
        public void Send(byte[] buf, int len, int deviceId)
        {
            clientMap[deviceId].Send(buf, len);
        }

        /// <summary>
        /// 发送逻辑区段信息
        /// </summary>
        /// <param name="buf"></param>
        /// <param name="byteFlag"></param>
        internal void SendLogicSections(byte[] buf, int byteFlag)
        {
            logicSectionClient.Send(buf, byteFlag);
        }
    }
}
